package org.jeecg.modules.demo.ddyht.controller;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.ddyht.entity.*;
import org.jeecg.modules.demo.ddyht.service.IDdygCostService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.demo.ddyht.service.IDdygCzrzService;
import org.jeecg.modules.demo.ddyht.service.IDdygSupplierService;
import org.jeecg.modules.demo.ddyht.service.IJxcHbzjService;
import org.jeecg.modules.demo.jxcx.Utils.R;
import org.jeecg.modules.demo.jxcx.Utils.RandomUtil;
import org.jeecg.modules.demo.jxcx.po.JxcCost;
import org.jeecg.modules.demo.jxcx.po.JxcCzrz;
import org.jeecg.modules.demo.jxcx.po.JxcSupplier;
import org.jeecg.modules.demo.jxcx.service.JxcCostService;
import org.jeecg.modules.demo.jxcx.service.JxcCzrzService;
import org.jeecg.modules.demo.jxcx.service.JxcSupplierService;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 费用单
 * @Author: jeecg-boot
 * @Date:   2025-02-23
 * @Version: V1.0
 */
@Api(tags="费用单")
@RestController
@RequestMapping("/ddyht/jxcCost")
@Slf4j
public class DdygCostController extends JeecgController<DdygCost, IDdygCostService> {
	@Autowired
	private IDdygCostService ddygCostService;
	@Autowired
	private JxcCostService jxcCostService;
	@Autowired
	private JxcCzrzService jxcCzrzService;
	@Autowired
	private JxcSupplierService jxcSupplierService;
	@Autowired
	private IJxcHbzjService jxcHbzjService;
     @Autowired
     private YueController yueController;

	/**
	 * 分页列表查询
	 *
	 * @param ddygCost
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "费用单-分页列表查询")
	@ApiOperation(value="费用单-分页列表查询", notes="费用单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<DdygCost>> queryPageList(DdygCost ddygCost,
												 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												 HttpServletRequest req) {
		QueryWrapper<DdygCost> queryWrapper = QueryGenerator.initQueryWrapper(ddygCost, req.getParameterMap());
		Page<DdygCost> page = new Page<DdygCost>(pageNo, pageSize);
		IPage<DdygCost> pageList = ddygCostService.page(page, queryWrapper);
		List<DdygCost> company = ddygCostService.getBycompany(ddygCost.getUsername());
		if (StringUtils.isNotBlank(ddygCost.getType1())){
			List<DdygCost> list = new ArrayList<>();
			String type1 = ddygCost.getType1();
			if (type1.equals("only")){
				if (ddygCost.getType2().equals("model")){
					if (StringUtils.isBlank(ddygCost.getType3())){
						int size = company.size();
						int page2 = (size + 9) / 10;
						pageList.setTotal(size);
						pageList.setPages(page2);
						pageList.setRecords(company);
						return Result.OK(pageList);
					}
					String type3 = ddygCost.getType3();
					for (int i = 0; i < company.size(); i++) {
						if (StringUtils.containsIgnoreCase(company.get(i).getFreight(),type3)){
							list.add(company.get(i));
						}
					}
				}
			}
			int size = list.size();
			int page2 = (size + 9) / 10;
			pageList.setTotal(size);
			pageList.setPages(page2);
			pageList.setRecords(list);
			return Result.OK(pageList);
		}
		int size = company.size();
		int page2 = (size + 9) / 10;
		pageList.setTotal(size);
		pageList.setPages(page2);
		pageList.setRecords(company);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param ddygCost
	 * @return
	 */
	@AutoLog(value = "费用单-添加")
	@ApiOperation(value="费用单-添加", notes="费用单-添加")
	@RequiresPermissions("ddyht:jxc_cost:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody DdygCost ddygCost) {

		LocalDateTime now = LocalDateTime.now();
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
		DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
		String formattedDateTime = now.format(formatter);
		String only1 = RandomUtil.generateRandomString();
		String id = now.format(formatter2) + only1;
		String paymentMethod = ddygCost.getBaozhuang();
		String companyId = ddygCost.getUsername();
		String ranjiao = ddygCost.getRanjiao();
		String freight = ddygCost.getFreight();
		ddygCost.setId(id);
		ddygCost.setOther(formattedDateTime);
		ddygCost.setCompanyId(companyId);
		JxcHbzj jxcHbzj = jxcHbzjService.selectbyPaymentMethod(paymentMethod, companyId);
		if (jxcHbzj != null){
//			JxcHbzj jxcHbzj = jxcHbzjService.selectbyPaymentMethod(PaymentMethod, CompanyId);
			jxcHbzj.setAmount(String.valueOf(new BigDecimal(jxcHbzj.getAmount()).subtract(new BigDecimal(ranjiao))));
			jxcHbzj.setCreateTime(formattedDateTime);
			jxcHbzjService.updateById(jxcHbzj);
		}else {
			JxcHbzj jxcHbzj2 = new JxcHbzj();
			jxcHbzj2.setAmount("-" + ranjiao);
			jxcHbzj2.setCompanyId(companyId);
			jxcHbzj2.setCreateTime(formattedDateTime);
			jxcHbzj2.setId(id);
			jxcHbzj2.setOther("费用单支出-"+freight);
			jxcHbzj2.setPaymethod(paymentMethod);
			jxcHbzjService.save(jxcHbzj2);

		}
		JxcCzrz jxcCzrz = new JxcCzrz();
		jxcCzrz.setId(DdygPiciController.setczrzid(id));
		jxcCzrz.setCompanyId(companyId);
		jxcCzrz.setOtherid("货币资金");
		jxcCzrz.setOrstate("费用单支出-"+freight);
		jxcCzrz.setType(paymentMethod);
		jxcCzrz.setInfor("-" + ranjiao);
		jxcCzrz.setCreatTime(formattedDateTime);
        yueController.setHbzj(jxcCzrz,paymentMethod,ranjiao,"-");
		jxcCzrzService.add(jxcCzrz);
        ddygCostService.save(ddygCost);
        return Result.OK("添加成功！");
//		if (jxcSupplier == null) {
//			JxcSupplier jxcSupplier1 = new JxcSupplier();
//			jxcSupplier1.setId(id);
//			jxcSupplier1.setCreateTime(formattedDateTime);
//			jxcSupplier1.setName(seller);
//			jxcSupplier1.setCompanyId(companyId);
//			jxcSupplier1.setAmount(ranjiao);
//			jxcSupplierService.save(jxcSupplier1);
//
//			JxcCzrz jxcCzrz1 = new JxcCzrz();
//			jxcCzrz1.setCompanyId(companyId);
//			jxcCzrz1.setInfor("姓名:"+seller+"金额"+ranjiao);
//			jxcCzrz1.setType("供应商新增");
//			R add = jxcCzrzService.add(jxcCzrz1);
//		} else {
//			BigDecimal add1 = (new BigDecimal(jxcSupplier.getAmount())).add(new BigDecimal(ranjiao));
//			jxcSupplier.setAmount(add1.toString());
//			jxcSupplierService.updateById(jxcSupplier);
//
//			JxcCzrz jxcCzrz1 = new JxcCzrz();
//			jxcCzrz1.setCompanyId(companyId);
//			jxcCzrz1.setInfor("姓名:"+seller+"金额+"+jxcSupplier.getAmount()+"->"+add1.toString());
//			jxcCzrz1.setType("供应商修改");
//			R add = jxcCzrzService.add(jxcCzrz1);
//		}
//		JxcCzrz jxcCzrz = new JxcCzrz();
//		jxcCzrz.setCompanyId(companyId);
//		jxcCzrz.setInfor("交易方:"+seller+"金额"+ranjiao+"类型"+ddygCost.getFreight());
//		jxcCzrz.setType("成本费用新增");
//		R add = jxcCzrzService.add(jxcCzrz);

//		ddygCostService.save(ddygCost);
//		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param ddygCost
	 * @return
	 */
	@AutoLog(value = "费用单-编辑")
	@ApiOperation(value="费用单-编辑", notes="费用单-编辑")
	@RequiresPermissions("ddyht:jxc_cost:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody DdygCost ddygCost) {

		log.info("成本费用修改数据" + ddygCost.toString());
		JxcCost old = jxcCostService.getBy(ddygCost.getId(), ddygCost.getCompanyId());
		String id  = ddygCost.getId();
		String oldAmount = old.getRanjiao();
		String newAmount = ddygCost.getRanjiao();
		String seller = ddygCost.getBaozhuang();
		String companyId = ddygCost.getCompanyId();
		BigDecimal subtract;
		JxcSupplier jxcSupplier;
		if ((new BigDecimal(newAmount)).compareTo(new BigDecimal(oldAmount)) > 0) {
			subtract = (new BigDecimal(newAmount)).subtract(new BigDecimal(oldAmount));
			jxcSupplier = this.jxcSupplierService.getBy(seller, companyId);
			jxcSupplier.setAmount(String.valueOf((new BigDecimal(jxcSupplier.getAmount())).add(subtract)));
			this.jxcSupplierService.updateById(jxcSupplier);

			JxcCzrz jxcCzrz1 = new JxcCzrz();
			jxcCzrz1.setId(DdygPiciController.setczrzid(id));
			jxcCzrz1.setCompanyId(companyId);
			jxcCzrz1.setInfor("姓名:"+seller+"金额+"+subtract.toString());
			jxcCzrz1.setType("供应商修改");
			R add = jxcCzrzService.add(jxcCzrz1);
		} else if ((new BigDecimal(newAmount)).compareTo(new BigDecimal(oldAmount)) < 0) {
			subtract = (new BigDecimal(oldAmount)).subtract(new BigDecimal(newAmount));
			jxcSupplier = this.jxcSupplierService.getBy(seller, companyId);
			jxcSupplier.setAmount(String.valueOf((new BigDecimal(jxcSupplier.getAmount())).subtract(subtract)));
			this.jxcSupplierService.updateById(jxcSupplier);

			JxcCzrz jxcCzrz1 = new JxcCzrz();
			jxcCzrz1.setId(DdygPiciController.setczrzid(id));
			jxcCzrz1.setCompanyId(companyId);
			jxcCzrz1.setInfor("姓名:"+seller+"金额-"+subtract.toString());
			jxcCzrz1.setType("供应商修改");
			R add = jxcCzrzService.add(jxcCzrz1);
		}

		JxcCzrz jxcCzrz = new JxcCzrz();
		jxcCzrz.setId(DdygPiciController.setczrzid(id));
		jxcCzrz.setCompanyId(companyId);
		jxcCzrz.setInfor("交易方:"+seller+"金额："+oldAmount+"->"+newAmount+"类型："+old.getFreight()+"->"+ddygCost.getFreight());
		jxcCzrz.setType("成本费用修改");
		R add = jxcCzrzService.add(jxcCzrz);
//		return (new R()).ok(jxcCostService.updateById(jxcCost));

		ddygCostService.updateById(ddygCost);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "费用单-通过id删除")
	@ApiOperation(value="费用单-通过id删除", notes="费用单-通过id删除")
	@RequiresPermissions("ddyht:jxc_cost:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		DdygCost ddygCost = ddygCostService.getById(id);
		String seller = ddygCost.getBaozhuang();
		String companyId = ddygCost.getCompanyId();
		JxcSupplier jxcSupplier = this.jxcSupplierService.getBy(seller, companyId);

		JxcCzrz jxcCzrz = new JxcCzrz();
		jxcCzrz.setId(DdygPiciController.setczrzid(id));
		jxcCzrz.setCompanyId(companyId);
		jxcCzrz.setInfor("交易方:"+seller);
		jxcCzrz.setType("成本费用删除");
		R add = jxcCzrzService.add(jxcCzrz);

		if (jxcSupplier != null) {
			BigDecimal a = (new BigDecimal(jxcSupplier.getAmount())).subtract(new BigDecimal(ddygCost.getRanjiao()));
			jxcSupplier.setAmount(a.toString());
			this.jxcSupplierService.updateById(jxcSupplier);

			JxcCzrz jxcCzrz1 = new JxcCzrz();
			jxcCzrz1.setId(DdygPiciController.setczrzid(id));
			jxcCzrz1.setCompanyId(companyId);
			jxcCzrz1.setInfor("姓名:"+seller+"金额-"+a.toString());
			jxcCzrz1.setType("供应商修改");
			R add1 = jxcCzrzService.add(jxcCzrz1);
		}

		ddygCostService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "费用单-批量删除")
	@ApiOperation(value="费用单-批量删除", notes="费用单-批量删除")
	@RequiresPermissions("ddyht:jxc_cost:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		List<String> list = Arrays.asList(ids.split(","));
		for (int i = 0; i < list.size(); i++) {
			String id = list.get(i);
			DdygCost ddygCost = ddygCostService.getById(id);
			String seller = ddygCost.getBaozhuang();
			String companyId = ddygCost.getCompanyId();
			JxcSupplier jxcSupplier = this.jxcSupplierService.getBy(seller, companyId);

			JxcCzrz jxcCzrz = new JxcCzrz();
			jxcCzrz.setId(DdygPiciController.setczrzid(id));
			jxcCzrz.setCompanyId(companyId);
			jxcCzrz.setInfor("交易方:"+seller);
			jxcCzrz.setType("成本费用删除");
			R add = jxcCzrzService.add(jxcCzrz);

			if (jxcSupplier != null) {
				BigDecimal a = (new BigDecimal(jxcSupplier.getAmount())).subtract(new BigDecimal(ddygCost.getRanjiao()));
				jxcSupplier.setAmount(a.toString());
				this.jxcSupplierService.updateById(jxcSupplier);

				JxcCzrz jxcCzrz1 = new JxcCzrz();
				jxcCzrz1.setId(DdygPiciController.setczrzid(id));
				jxcCzrz1.setCompanyId(companyId);
				jxcCzrz1.setInfor("姓名:"+seller+"金额-"+a.toString());
				jxcCzrz1.setType("供应商修改");
				R add1 = jxcCzrzService.add(jxcCzrz1);
			}
		}

		this.ddygCostService.removeByIds(list);
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "费用单-通过id查询")
	@ApiOperation(value="费用单-通过id查询", notes="费用单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<DdygCost> queryById(@RequestParam(name="id",required=true) String id) {
		DdygCost ddygCost = ddygCostService.getById(id);
		if(ddygCost ==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(ddygCost);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param ddygCost
    */
    @RequiresPermissions("ddyht:jxc_cost:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, DdygCost ddygCost) {
        return exportXls(request, ddygCost, DdygCost.class, "费用单");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("ddyht:jxc_cost:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, DdygCost.class);
    }

	 public ModelAndView exportXls(HttpServletRequest request, DdygCost object, Class<DdygCost> clazz, String title) {
		 // Step.1 组装查询条件
		 QueryWrapper<DdygCost> queryWrapper = QueryGenerator.initQueryWrapper(object, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 log.info("selections {}", selections);
		 if (oConvertUtils.isNotEmpty(selections)) {
			 log.info("selections {}", selections);
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 log.info("selectionList {}", selectionList);
			 queryWrapper.in("id",selectionList);
		 }
		 List<DdygCost> exportList = new ArrayList<DdygCost>();
		 // Step.2 获取导出数据
		 if (oConvertUtils.isNotEmpty(selections)){
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 List<DdygCost> ddygCosts = new ArrayList<DdygCost>();
			 for (int i = 0; i < selectionList.size(); i++) {
				 String id = selectionList.get(i);
				 ddygCosts = ddygCostService.getByallId(object.getUsername(), id);
				 for (int i1 = 0; i1 < ddygCosts.size(); i1++) {
					 ddygCosts.get(i1).setOther(ddygCosts.get(i1).getOther().substring(0, 10));
					 exportList.add(ddygCosts.get(i1));
				 }
			 }
		 }else {
			 List<DdygCost> bycompany = ddygCostService.getBycompany(object.getUsername());
			 for (int i = 0; i < bycompany.size(); i++) {
				 bycompany.get(i).setOther(bycompany.get(i).getOther().substring(0, 10));
			 }
			 exportList = bycompany;
		 }
		 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
		 exportList.sort((o1, o2) -> {
			 LocalDate date1 = LocalDate.parse(o1.getOther(), formatter);
			 LocalDate date2 = LocalDate.parse(o2.getOther(), formatter);
			 return date2.compareTo(date1); // 最新在前
		 });
//		 List<DdygSale> exportList = service.list(queryWrapper);

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.FILE_NAME, title);
		 mv.addObject(NormalExcelConstants.CLASS, clazz);
		 //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
		 ExportParams exportParams=new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title);
		 exportParams.setImageBasePath("C:/upload/sc");
//		 exportParams.setImageBasePath(jeecgBaseConfig.getPath().getUpload());
		 //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
		 mv.addObject(NormalExcelConstants.PARAMS,exportParams);
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
	 }}
